<template>
  <div class="app-container">
    <header>
      <el-button type="primary" size="small" @click="showDialog = true">添加用户</el-button>
      <!-- 表单内容 -->
      <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
        <el-form ref="ruleForm" label-width="120px" :model="ruleForm" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用" prop="state">
            <el-switch size="mini" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini">确定</el-button>
                <el-button size="mini">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>
    </header>
    <section>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column align="center" prop="name" label="角色" width="249">
          <template slot-scope="scope">
            <!-- <span>{{ scope.row }}</span> -->
            <span v-if="!scope.row.isEdit">{{ scope.row.name }}</span>
            <input v-else type="text" :value="scope.row.editRow.name" />
          </template>
        </el-table-column>
        <!-- <el-table-column prop="state" label="启用" width="249" /> -->
        <!-- 第一种: 插槽 -->
        <el-table-column align="center" label="启用" width="150">
          <template slot-scope="scope">
            <!-- <span>{{ scope.row.state === 1 ? '已启用' : '未启用' }}</span> -->
            <span v-if="!scope.row.isEdit">{{ scope.row.state === 1 ? '已启用' : '未启用' }}</span>
            <el-switch
              v-else
              v-model="scope.row.editRow.state"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column>
        <!-- 第二种: element-ui 方法数据  -->
        <!-- <el-table-column prop="state" :formatter="formState" label="启用" width="250" /> -->
        <!-- 第三种: 过滤器 -->
        <!-- <el-table-column label="启用" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.state | handleState1 | handleState2 |handleState3 }}</span>
          </template>
        </el-table-column>-->
        <el-table-column align="center" prop="description" label="描述" width="300">
          <template slot-scope="scope">
            <span v-if="!scope.row.isEdit">{{ scope.row.description }}</span>
            <el-input
              v-else
              v-model="scope.row.editRow.description"
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <div v-if="!scope.row.isEdit">
              <el-button
                type="text"
                size="small"
                @click="isVisible =true; roleId =scope.row.id"
              >分配权限</el-button>
              <el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
              <el-button type="text" size="small">
                <!-- 删除 -->
                <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(scope.row.id)">
                  <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
                </el-popconfirm>
              </el-button>
            </div>
            <div v-else>
              <el-button type="primary" size="mini" @click="editSubmit(scope.row)">确定</el-button>
              <el-button size="mini" @click="scope.row.isEdit = false">取消</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </section>
    <DistributAuth :is-visible.sync="isVisible" :role-id="roleId" />
  </div>
</template>
<script>
import { getRoleList, updateRole, delRole } from '@/api/role'
import DistributAuth from './components/distributAuth'
export default {
  name: 'Role',
  components: {
    DistributAuth
  },
  // filters: {
  //   handleState1: function(value) {
  //     return value === 1 ? '已启用' : ' 未启用'
  //   },
  //   handleState2: function(value) {
  //     return '<h2>' + value + '</h2>'
  //   },
  //   handleState3: function(value) {
  //     return value.replace('<h2>', '<h2 style="color :pink">')
  //   }
  // },
  // vue中data里的数据都具有响应式，但是后面往data里添加的数据（深层的）有可能没有响应式
  data() {
    return {
      roleId: 0,
      isVisible: false,
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 8,
      showDialog: false,
      ruleForm: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        state: [
          { required: true, trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ] }

    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 编辑
    // async edit(row) {
    edit(row) {
      // 目的：把isEdit属性去掉，但是又不能把row里面的去掉
      // row.isEdit = !row.isEdit
      // 深拷贝row里的数据
      // Object.assign 的作用：把后面对象里的属性全部合并到第一个对象里，最后返回第一个对象
      // const o = Object.assign({}, row)
      const o = { ...row }
      // editRow 里不需要isEdit 变量，让editRow里的数据变得干净一点
      delete o.isEdit
      // 下面这行代码没有响应式，所以应该用$set
      // row.editRow = o
      this.$set(row, 'editRow', o)
      // delete o.isEdit
      // await updateRole(o)
      // 添加完之后row数据个格式是：
      // row = {
      //   name: 'xx',
      //   state: 1,
      //   decription: 'xxx',
      //   editRow: {
      //     name: 'xx',
      //     state: 1,
      //     decription: 'xxx'
      //   }
      // }
      // eslint-disable-next-line require-atomic-updates
      row.isEdit = true
    },
    // 点击编辑里的确定按钮，发送请求
    async editSubmit(row) {
      // 目的：把isEdit属性去掉，但是又不能把row里面的去掉
      // const o = { ...row }
      // delete o.isEdit
      const o = { ...row.editRow }
      await updateRole(o)
      this.$message.success('修改成功')
      // 另一种刷新页面的方案：把row.editRow里的数据同步到row里
      Object.assign(row, row.editRow)
      // eslint-disable-next-line require-atomic-updates
      row.isEdit = false
    },
    // 获取数据
    async getRoleList() {
      const { data } = await getRoleList({
        page: this.pageNum,
        pagesize: this.pageSize
      })
      console.log(data)
      this.total = data.total
      this.pageNum++
      // 处理服务器返回的数据
      data.rows.forEach(item => {
        // item.isEdit = false
        this.$set(item, 'isEdit', false)
      })
      this.tableData = data.rows
    },
    // 处理启动数据
    formState(row, column, cellValue, index) {
      return cellValue === 1 ? '已启用' : '未启用'
    },
    // 当用户改变页码 会执行函数
    handleCurrentChange(val) {
      this.pageNum = val
      console.log(val)
      this.getRoleList()
    },
    // 删除
    confirmDel(id) {
      delRole(id)
      this.$message.success('删除角色成功')
      // 当删除最后一个数据时
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    }
    // 添加
    // async addRole() {
    //   const { data } = await addRole({

    //   })
    //   console.log(data)
    // }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  padding-bottom: 20px;
}
header {
  padding: 10px;
}
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
section {
  padding: 5px 50px;
}
</style>
